var express = require('express');
var router = express.Router();
var db = require('../core/mysql.js');
var cookie = require('cookie');
var parse = require('../public/javascripts/parse.js');

router.get('/home', function(req, res, next) {
  req.cookies = parse.JSONCookies(cookie.parse(req.headers.cookie)); 
  var user = req.cookies.user;
  if(!user || !user.id){
    res.render('users/login.art' ,{title:'用户登录'});
    return ;
  }
  // 查询自己发布的博客
  blogList({createId:user.id},function(err,result){
	  	if(err){
	  		console.error(err);
	  		return;
	  	}
	  	res.render('home' ,{title:'博客主页',user:user,myBlogList:result});
  });
});
/* GET home page. */
router.get('/index', function(req, res, next) {
	res.redirect('/');
});
router.get('/', function(req, res, next) {
  blogList({},function(err,result){
	  	if(err){
	  		console.error(err);
	  		return;
	  	}
	  	req.cookies = parse.JSONCookies(cookie.parse(req.headers.cookie)); 
	  	var user = req.cookies.user;
	  	res.render('index.art' ,{layout:'layout.art',title:'Express1',user:user,blogList:result});
  });
});

function blogList(blog={},callback){
	var sql = "select a.id,a.title,a.content,a.create_id userId,a.create_time createTime,b.show_name userName from blog_publish a left join blog_user b on a.create_id=b.id where 1=1";
	var queryObj = {};
	if(blog.createId){
		sql += " and a.create_id=:createId";
		queryObj.createId = blog.createId;
	}
	db.query(sql+" order by a.create_id desc",queryObj,function(err,result){
		if(err){
			console.error(err);
			return;
		}
		callback(err,result);
	});
}

module.exports = router;
